package com.toptech.testapp;

import java.lang.reflect.Field;

import android.view.Window;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;

public class KeyFeatures {

    public static final int KEY_FEATURE_POWER_PASS_TO_USER = 1 << 0;

    public static final int KEY_FEATURE_HOME_PASS_TO_USER = 1 << 1;

    public static final int KEY_FEATURE_VOLUME_PASS_TO_USER = 1 << 2;

    public static final int KEY_FEATURE_APP_LAUNCHER_PASS_TO_USER = 1 << 3;

    public static final int KEY_FEATURE_TV_INPUT_SOURCE_PASS_TO_USER = 1 << 4;

    public KeyFeatures() {
    }

    public void setKeyFeature(Window window, boolean intercept) {
        if (window == null) {
            return;
        }
        WindowManager.LayoutParams attributes = window.getAttributes();
        try {
            Field field = LayoutParams.class.getField("keyFeatures");
            field.setAccessible(true);

            int keyFeatures = field.getInt(attributes);
            if (intercept) {
                // 拦截类型：遥控器/按键板
                //keyFeatures |= KEY_FEATURE_TYPE_IR;
                //keyFeatures |= KEY_FEATURE_TYPE_KEYPAD;

                // 请根据实际需求做出拦截
                // 拦截POWER键
                keyFeatures |= KEY_FEATURE_POWER_PASS_TO_USER;
                // 拦截HOME键
                 keyFeatures |= KEY_FEATURE_HOME_PASS_TO_USER;
                // 拦截音量键（静音、音量+、音量-）
                 keyFeatures |= KEY_FEATURE_VOLUME_PASS_TO_USER;
            } else {
                // 拦截类型：遥控器/按键板
                //keyFeatures &= ~KEY_FEATURE_TYPE_IR;
                //keyFeatures &= ~KEY_FEATURE_TYPE_KEYPAD;

                // 取消拦截POWER键
                keyFeatures &= ~KEY_FEATURE_POWER_PASS_TO_USER;
                // 取消拦截HOME键
                 keyFeatures &= ~KEY_FEATURE_HOME_PASS_TO_USER;
                // 取消拦截音量键（静音、音量+、音量-）
                 keyFeatures &= ~KEY_FEATURE_VOLUME_PASS_TO_USER;
            }
            field.setInt(attributes, keyFeatures);

            window.setAttributes(attributes);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
